# =================== 导入模块 ===============
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from jwt import exceptions
import jwt
from django.conf import settings



class MyJwtAuthentication(BaseAuthentication):

    def authenticate(self, request):
        # 获取token
        token = request.META.get('HTTP_TOKEN', None)
        # 获取key, 也是加密
        key = settings.SECRET_KEY
        # 开始验证
        try:
            payload = jwt.decode(token, key, True)
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({'code':0, 'error': "Token已失效！"})
        except jwt.DecodeError:
            raise AuthenticationFailed({'code': 0, 'error': "认证失败！"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({'code': 0, 'error': "无效的Token！"})
        except:
            raise AuthenticationFailed({'code': 0, 'error': "未知的错误！"})

        return payload, token

# return(payload, token)
# payload -- request.user.id ---> 当前用户的Id
#            request.user.name ---> 当前用户的姓名

# token ---- 可以访问到jwt key   --- > request.token
 # authenticate（） 返回值三种场景：
 # 1. 验证成功 -- return payload, token --- 可以通过request.user, request.token
 # 2. False --- 验证失败！ -- raise exceptions.AuthenticationFailed(‘用户认证失败’)
 # 3. None --- 进行下一种认证！


class MyAuthedPermission(BasePermission):
    # 定义一个message --- 如果返回False，携带message
    message = "您无权访问数据，必须要登录后才可以访问！"
    # 必须要重新方法
    def has_permission(self, request, view):
        # 在request.user判断
        if request.user:
            return True
        return False


# 只有人力资源部才可以访问
class IsHRPermisson(BasePermission):
    message = "您不属于HR部门，您无权访问数据！"
    def has_permission(self, request, view):
        print(request.user)
        # 获取request.user信息
        roles = request.user.get('roles')
        # 遍历
        for item in roles:
            if item.get('name') == '人力资源部':
                return True

        return False

